package com.collabscm.pf.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.collabscm.pf.exception.UncheckedException;
import com.collabscm.pf.logging.Logger;
import com.collabscm.pf.logging.LoggerFactory;
import com.collabscm.pf.util.JsonUtils;

/**
 * Web层的工具类，包括对HttpServletRequest和HttpServletResponse处理的封装等。
 * @author Zeng Raoxing
 */
public class WebUtils {
	private static Logger logger = LoggerFactory.getLogger(WebUtils.class);
	/**
	 * Response中的contentType
	 */
	private static String jsonContentType;
	/**
	 * 发给客户端说明是什么字符集
	 */
	private static String charsetName;
	
	/**
	 * 从客户端的Cookie中获得指定的信息
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		return org.springframework.web.util.WebUtils.getCookie(request, name);
	}
	
	public static void responseJson(Object jsonObject) {
		responseJson(ServletActionContext.getResponse(), jsonObject);
	}
	
	public static void responseJson(HttpServletResponse response, Object jsonObject) {
		String jsonString = JsonUtils.toJsonObjectString(jsonObject);
		responseJsonString(response, jsonString);
	}
	
	/**
	 * 直接将字Json的字符串写入到Response中
	 * 
	 * @param response
	 * @param jsonString Json的字符串
	 */
	public static void responseJsonString(HttpServletResponse response, String jsonString) {
        response.setContentType(jsonContentType);
        byte[] bytes;
		try {
			bytes = jsonString.getBytes(charsetName);
		} catch (UnsupportedEncodingException e) {
			throw new UncheckedException(e);
		}
        response.setContentLength(bytes.length);
        try {
			OutputStream os = response.getOutputStream();
			os.write(bytes);
			os.flush();
			logger.debug("往客户端发送的Json串为：{}", jsonString);
		} catch (IOException e) {
			logger.error("在往Response中写入Json字符串的时候发生异常。", e);
			throw new UncheckedException(e);
		}
	}
	
	public static class Configuration {
		/**
		 * 设置JSON发送的ContentType的头
		 * @param jsonContentType
		 */
		public void setJsonContentType(String jsonContentType) {
			WebUtils.jsonContentType = jsonContentType;
		}
		/**
		 * 发给客户端说明是什么字符集
		 */
		public void setCharsetName(String charsetName) {
			WebUtils.charsetName = charsetName;
		}
	}
	
}
